package com.mayuanfei.springboot11.handler;

import com.mayuanfei.springboot11.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.stream.Collectors;

/**
 * 全局异常处理
 *
 * @author 老马
 * @date 2023-06-15 14:27
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 默认全局异常处理。
     * @param e the e
     * @return ResultData
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public R<Void> exception(Exception e) {
        log.error("全局异常信息 ex={}", e.getMessage(), e);
        return R.fail(e.getMessage());
    }

    /**
     * 捕获校验框架Validator抛出的异常
     * BindException: 表单数据校验失败
     * ConstraintViolationException: 单参数校验失败
     * MethodArgumentNotValidException: RequestBody校验失败
     */
    @ExceptionHandler(value = {BindException.class, ConstraintViolationException.class, MethodArgumentNotValidException.class})
    public R<Void> handleValidatedException(Exception e) {
        if (e instanceof MethodArgumentNotValidException) {
            // RequestBody校验失败
            MethodArgumentNotValidException ex = (MethodArgumentNotValidException) e;
            return R.fail(ex.getBindingResult().getAllErrors().stream()
                            .map(ObjectError::getDefaultMessage)
                            .collect(Collectors.joining("; "))
            );
        } else if (e instanceof ConstraintViolationException) {
            // 单参数校验失败
            ConstraintViolationException ex = (ConstraintViolationException) e;
            return R.fail(ex.getConstraintViolations().stream()
                            .map(ConstraintViolation::getMessage)
                            .collect(Collectors.joining("; "))
            );
        } else if (e instanceof BindException) {
            // 表单数据校验失败
            BindException ex = (BindException) e;
            return R.fail(ex.getAllErrors().stream()
                            .map(ObjectError::getDefaultMessage)
                            .collect(Collectors.joining("; "))
            );
        }
        return R.fail();
    }
}